package org.activequant.container.context;

import java.util.Map;

/**
 * TradeSystemContext that is configured by listing all services explicitly.
 * Service of same type can be listed multiple times (under different names).
 * Note that all names has to be different.<br/>
 * A TradeSystemContextBase subclass. Holds the following associated variable:
 * <ul>
 * <li>exportedBeans(Map&lt;String,Object&gt;)</li>
 * </ul>
 * <p>
 * This context provides "default" service resolution as follows:
 * if requested name is wildcard (null), and there are more than one
 * service of this type, it returns the first service in the order of
 * declaration.
 * </p>
 * <b>History:</b><br>
 *  - [01.16.2008] Created (Mike Kroutikov)<br>
 *
 *  @author Mike Kroutikov
 */
public final class BeanTradeSystemContext extends TradeSystemContextBase {
	/**
	 * private Map&lt;String,Object&gt; exportedBeans = new java.util.LinkedHashMap&lt;String,Object&gt;();
	 */
	private Map<String,Object> exportedBeans = new java.util.LinkedHashMap<String,Object>();
	/**
	 * sets the associated exportedBeans(Map&lt;String,Object&gt;) with the given val(Map&lt;String,Object&gt;)
	 * @param val
	 */
	public void setExport(Map<String,Object> val) {
		exportedBeans = val;
	}
	/**
	 * returns the associated exportedBeans(Map&lt;String,Object&gt;)
	 * @return
	 */
	public Map<String,Object> getExport() {
		return exportedBeans;
	}
	/**
	 * tries to find and return the T object mapped under the given name(String) in the associated exportedBeans(Map&lt;String,Object&gt;) (casts it to the given clazz(Class&lt;T&gt;)).
	 * Or if the given name(String) is null, it just returns the first Object value in the associated exportedBeans(Map&lt;String,Object&gt;) whose Class can be assigned from the given clazz(Class&lt;T&gt;).
	 */
	@Override
	protected <T> T lookup(Class<T> clazz, String name) {
		if(name != null) {
			Object bean = exportedBeans.get(name);
			if(bean == null) {
				return null;
			}
			if(clazz.isAssignableFrom(bean.getClass())) {
				return clazz.cast(bean);
			}
			return null;
		}
		for(Object bean : exportedBeans.values()) {
			if(clazz.isAssignableFrom(bean.getClass())) {
				return clazz.cast(bean);
			}
		}
		return null;
	}
}
